﻿using System;
using System.Collections.Generic;
using System.Data.Entity;
using System.Linq;
using System.Net;
using System.Web;
using System.Web.Http.Results;
using System.Web.Mvc; // needed for lambda includes

using TheCup.ApiControllers;


namespace TheCup.Controllers
{
    public class BlogController : Controller
    {
        ApiControllers.BlogController bc = new ApiControllers.BlogController();
        ApiControllers.PlayerController pc = new ApiControllers.PlayerController();
        CommentController cc = new CommentController();
        
        public ActionResult Index()
        {
            var data = bc.Get().Take(50);
            return View(data);
        }

        public ActionResult Details(int id)
        {
            Blog blog = bc.Get().Where(b => b.Id == id).FirstOrDefault();

            blog.Comments = cc.Get(blog.OldId, blog.Id, CommentEntity.Blog);
            
            return View(blog);
        }

        [Authorize]
        public ActionResult Edit(int id)
        {
            Blog b = bc.Get(id);
            return View(b);
        }

        [Authorize]
        [HttpPost]
        public ActionResult Edit(Blog b)
        {
            if (ModelState.IsValid)
            {
                if (b.AuthorId == pc.GetLoggedInPlayer().Id)
                {
                    bc.Put(b.Id, b);
                }
                else
                {
                    ModelState.AddModelError("owner", "Du er ikke bloggens ejermand!");
                    return View(b);
                }
            }

            return RedirectToAction("Details", new { id = b.Id });
        }

        [Authorize]
        public ActionResult Create()
        {
            ViewBag.Player = pc.GetLoggedInPlayer();
            return View();
        }

        [Authorize]
        [HttpPost]
        public ActionResult Create(Blog b)
        {
            bc.Post(b);
            return Redirect("~/");
        }
    }
}
